package io.vertx.example.web.form

import com.eliza.v.http.VertxTools
import com.eliza.v.http.resp.Image
import io.vertx.core.AbstractVerticle
import io.vertx.core.Promise
import io.vertx.core.http.HttpHeaders
import io.vertx.core.http.HttpServerOptions
import io.vertx.core.net.PemKeyCertOptions
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import io.vertx.ext.web.handler.BodyHandler


/*
* @author <a href="http://tfox.org">Tim Fox</a>
*/
class From : AbstractVerticle() {
    override fun start(startPromise: Promise<Void>?) {
        super.start(startPromise)
//        form()
    }

    private fun form() {
        val router = Router.router(vertx)

        // Enable multipart form data parsing
        router.route().handler(BodyHandler.create())
        router.route("/form").handler { routingContext: RoutingContext ->
            routingContext.response().putHeader("content-type", "text/html").end(
                """<form action="/form" method="post">
    <div>
        <label for="name">Enter your name:</label>
        <input type="text" id="name" name="name" />
    </div>
    <div class="button">
        <button type="submit">Send</button>
    </div></form>"""
            )
        }

        // handle the form
        router.post("/form/value").handler { ctx: RoutingContext ->
            ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/plain")
            // note the form attribute matches the html form element name.
            ctx.response().end("Hello " + ctx.request().getParam("name") + "!")
        }
        VertxTools.result(vertx, this, "", router, 8080)
    }

    private fun http2_image() {
        var path="com/eliza/v/http/resp/coin.png"
        val image = Image(vertx, path)

        val router = Router.router(vertx)

        router.get("/").handler { ctx: RoutingContext ->
            ctx.response()
                .putHeader("Content-Type", "text/html")
                .end(image.generateHTML(16))
        }

        router["/img/:x/:y"].handler { ctx: RoutingContext ->
            ctx.response()
                .putHeader("Content-Type", "image/png")
                .end(image.getPixel(ctx.pathParam("x").toInt(), ctx.pathParam("y").toInt()))
        }

        vertx.createHttpServer(
            HttpServerOptions()
                .setSsl(true)
                .setUseAlpn(true)
                .setPemKeyCertOptions(
                    PemKeyCertOptions().setKeyPath("http/keys/jwt/server-key.pem").setCertPath("tls/server-cert.pem")
                )
        ).requestHandler(router)
            .listen(8443)
    }


}